<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="88%"
    v-dialog-drag
    :close-on-click-modal="false"
    top="3vh"
    @close="dialogClose()"
    @open="dialogOpen()"
  >
    <el-collapse
      class='collapse-list'
      :value="[
        'base',
        'product',
        'material'
      ]"
    >
      <baseInfo :mode="mode" :orderDetail="orderDetail" @getPrescDetail="getPrescDetail" ref="base" @actual-time-change="refreshActualQuantity" v-if='isShowBase'/>
      <productInfo :mode="mode"  :productList="productList" :orderDetail="orderDetail" ref='productInfo' @refershOrderQtys='refershOrderQtys'/>
      <materialInfo :mode="mode" :materialList="materialList" :orderDetail="orderDetail" ref='material'/>
    </el-collapse>

    <div slot="footer" class="dialog-footer" v-if='mode !== "look" && mode !== "history"'>
      <el-button size="small" @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" size="small" v-if='mode == "add"' @click="handleSubmit">提交</el-button>
      <el-button type="primary" size="small" v-if='mode == "confirm"' @click="handleConfirm">确认工单</el-button>
      <el-button type="primary" size="small" v-if='mode == "cancel"' @click="handleCancel">取消确认</el-button>
      <el-button type="primary" size="small" v-if='mode == "update"' @click="handleUpdate">更新工单</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {submitOrder,confirmOrder,cancelOrder,updateOrder,deleteOrderByIds,erpPrescDetail,getOrderDetail,getOrderCloseDetail} from "@/api/workOrder/confirmClose";
import { getActualQtyByOrderIdAndTime } from "@/api/shifts/shiftHandover";
import baseInfo from "../components/baseInfo";
import productInfo from "../components/productInfo";
import materialInfo from "../components/materialInfo";
import { mapState,mapActions } from "vuex";
export default {
  components: {baseInfo,productInfo,materialInfo },
  props:{
    row:{
      type:Object,
      default:()=>{}
    },
    mode:{
      type:String,
      default:""
    },
    title:{
      type:String,
      default:"工单详情"
    },
    visible: {
      type: Boolean,
      default: false
    },
  },

  data() {
    return {
      loading: false,
      isShowBase:false,
      productList:[],
      materialList:[],
      orderDetail:{}
    };
  },

  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val)
      },
      get() {
        return this.visible
      }
    }
  },

  methods: {
    dialogClose() {
      this.loading = false;
      this.resetFormData();
      const baseForm = this.$refs["base"];
      baseForm.resetFormData();
      this.isShowBase = false;
    },

    dialogOpen() {
      this.isShowBase = true;
      if (!this.row?.id) {
        this.resetFormData();
        return
      }
      if(this.mode == "update"){
        this.getOrderCloseDetail()
      }
      else{
        this.getOrderDetail()
      }
    },

    //查询工单详情(确认及取消确认场景使用)
    getOrderDetail(){
      getOrderDetail(this.row.id)
      .then(res=>{
        if (res.code == 200 && res.data) {
          this.orderDetail = res.data;
          this.productList.push({
            erpItemCode:this.orderDetail.itemCode,
            erpItemName:this.orderDetail.itemName,
            erpPackageNumber:this.orderDetail.planQuantity,
            actualQuantity:this.orderDetail.actualQuantity,
            erpItemSpec:this.orderDetail.itemUnit
          })
          this.materialList = this.orderDetail?.orderMaterialDtos;
          if(this.materialList?.length){
            this.materialList.forEach(ele => {
              this.$set(ele,"usedConsumeQty",Number(ele.theoryConsumeQty)+Number(ele.actualWastageQty))
            })
          }
        } else {
          this.orderDetail = {};
          this.resetFormData()
        }
      }).catch(() => {
        this.resetFormData()
      })
    },

    //查询生产工单详情--工单关闭场景
    getOrderCloseDetail(){
      getOrderCloseDetail(this.row.id)
      .then(res=>{
        if (res.code == 200 && res.data) {
          this.orderDetail = res.data;
          this.productList.push({
            erpItemCode:this.orderDetail.itemCode,
            erpItemName:this.orderDetail.itemName,
            erpPackageNumber:this.orderDetail.planQuantity,
            actualQuantity:this.orderDetail.actualQuantity,
            erpItemSpec:this.orderDetail.itemUnit
          })
          this.materialList = this.orderDetail?.orderMaterialDtos;
          this.materialList.forEach(ele => {
            this.$set(ele,"usedConsumeQty",Number(ele.theoryConsumeQty)+Number(ele.actualWastageQty))
          })
        } else {
          this.orderDetail = {};
          this.resetFormData();
        }
      }).catch(() => {
        this.resetFormData()
      })
    },

    //获取处方详情
    getPrescDetail(prescId){
      erpPrescDetail(prescId)
      .then(res=>{
        this.materialList = [];
        this.productList = [];
        if (res.code == 200 && res.data) {
          const productItem = res.data?.erpFormulaDto?.productItem;
          this.materialList = res.data?.erpFormulaDto?.materialItems;
          this.materialList = this.materialList.map(ele => {
            return {
              itemNo:ele.erpItemCode,
              itemName:ele.erpItemName,
              itemUnit:ele.erpItemSpec
            }
          })
          this.productList.push(productItem);
        } else {
          this.materialList = [];
          this.productList = [];
          this.resetFormData()
        }
      }).catch(() => {
        this.resetFormData()
      })
    },

    // 创建工单
    handleSubmit(){
      this.loading = true;
      const baseForm = this.$refs["base"];
      baseForm.$refs.ruleForm
      .validate((flag) => {
        if (flag) {
          const parmas = baseForm.form;
          let planQuantity = ""
          let numList = this.productList.map(ele => ele.erpPackageNumber);
          numList.forEach(item => {
            planQuantity += item
          });
          if(planQuantity == ''){
            this.msgWarning("请输入WIP数量");
            return
          }
          parmas.planQuantity = planQuantity;
          submitOrder(parmas).then(res => {
            if (res.code == 200) {
              this.msgSuccess("操作成功")
              this.$emit("submit-success")
              this.dialogVisible = false
            } else {
              this.msgError(res.msg || "操作失败")
            }
            this.loading = false
          }).catch(() => {
            this.msgError("操作失败")
            this.loading = false
          })
        }
        else {
          this.loading = false
        }
      })
    },

    //确认工单
    handleConfirm(){
      this.loading = true;
      const baseForm = this.$refs["base"];
      baseForm.$refs.ruleForm
      .validate((flag) => {
        if (flag) {
          const formData = baseForm.form;
          const parmas = {
            orderSn:formData.orderSn,
            id:this.row.id,
            actualStarttime:formData.actualStarttime
          }
          confirmOrder(parmas).then(res => {
            if (res.code == 200) {
              this.msgSuccess("操作成功")
              this.$emit("submit-success")
              this.dialogVisible = false
            } else {
              this.msgError(res.msg || "操作失败")
            }
            this.loading = false
          }).catch(() => {
            this.msgError("操作失败")
            this.loading = false
          })
        }
        else {
          this.loading = false
        }
      })
    },

    //取消确认工单
    handleCancel(){
      this.$confirm("是否确定取消该生产工单？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
      }).then(() => {
        this.loading = true;
        const parmas = {
          id:this.row.id
        }
        cancelOrder(parmas).then(res => {
          if (res.code == 200) {
            this.msgSuccess("操作成功")
            this.$emit("submit-success")
            this.dialogVisible = false
          } else {
            this.msgError(res.msg || "操作失败")
          }
          this.loading = false
        }).catch(() => {
          this.msgError("操作失败")
          this.loading = false
        })
      }).catch(() => {
        this.dialogVisible = false
      });
    },

    // 确认更新工单
    async handleUpdate(){
      await this.$refs.productInfo.checkChangeNum();
      const baseForm = this.$refs["base"];
      baseForm.$refs.ruleForm
      .validate((flag) => {
        if (flag) {
          const formData = baseForm.form;
          const orderMaterial = this.$refs["material"].tableList
          let ptsPickingQty = "";
          let ptsRefundQty = "";
          let actualWastageQty = "";
          orderMaterial.forEach(ele => {
            ptsPickingQty += ele.ptsPickingQty;
            ptsRefundQty += ele.ptsRefundQty;
            actualWastageQty += ele.actualWastageQty;
          });
          if(ptsPickingQty == ''){
            this.msgWarning("请输入领料量");
            return
          }
          if(ptsRefundQty == ''){
            this.msgWarning("请输入预计退料量");
            return
          }
          if(actualWastageQty == ''){
            this.msgWarning("请输入损耗量");
            return
          }
          const parmas = {
            id: this.orderDetail.id,
            actualStarttime:formData.actualStarttime,
            actualEndtime: formData.actualEndtime,
            collectedQuantity: this.orderDetail.collectedQuantity,
            actualQuantity: this.orderDetail.actualQuantity,
            orderMaterialDtos:orderMaterial,
            orderSn:formData.orderSn,
            erpOrderNo:this.orderDetail.erpOrderNo
          }
          updateOrder(parmas).then(res => {
            if (res.code == 200) {
              this.msgSuccess("操作成功")
              this.$emit("submit-success")
              this.dialogVisible = false
            } else {
              this.msgError(res.msg || "操作失败")
            }
            this.loading = false
          }).catch(() => {
            this.msgError("操作失败")
            this.loading = false
          })
        }else {
          this.loading = false
        }
      })
    },
    // 修改实际开始/结束时间时，刷新产品实际产量
    refreshActualQuantity(form) {
      // 更新实际产量
      const { id}  = this.orderDetail;
      const { actualStarttime, actualEndtime } = form;

      // 实际开始实际和实际结束时间任一为空时，不刷新产量
      if (!actualStarttime || !actualEndtime) {
        return;
      }

      const param = {
        id,
        actualStarttime,
        actualEndtime,
      };
      getActualQtyByOrderIdAndTime(param).then(res=>{
        // res.data=0也不覆盖
        if (this.$refs.productInfo && res?.data) {
          this.productList[0].actualQuantity = res.data;
          this.$refs.productInfo.changNum(res.data);
        }
      })
    },

    //更新工单时，刷新填写的产量和物料用量信息,获取最新实际产量
    refershOrderQtys(tableList,actualQuantity){
      if(tableList?.length){
        tableList.forEach(ele => {
          this.$set(ele,"usedConsumeQty",Number(ele.theoryConsumeQty)+Number(ele.actualWastageQty))
        })
      }
      this.orderDetail.actualQuantity = actualQuantity;
      this.$refs["material"].tableList = tableList;
    },

    resetFormData() {
      this.orderDetail = {};
      this.productList = [];
      this.materialList = [];
    },
  },
};
</script>
<style lang="scss" scoped>
.top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.pagination-container {
  margin: 0;
}

.status-class-a{
  color: #D9001B;
  font-weight: 600;
}

.status-class-b{
  color: #F59A23;
  font-weight: 600;
}
.status-class-c{
  color: #88c446;
  font-weight: 600;
}
.status-class-d{
  color: #666666;
  font-weight: 600;
}
.btn-wrap{
  padding-bottom:1.25rem;
  text-align: right;
}
</style>
